package com.kakalog.main.gpt;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.*;


import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @auther 夏杨
 **/
@RestController
public class ChatGptController {
    @PostMapping("/ChatGptCompletions")
    public String ChatGptCompletions(@RequestBody List<ReqMessage> contents) throws IOException, InterruptedException {
        HttpClient client = HttpClient.newHttpClient();
        String url = "https://apikeyplus.com/v1/chat/completions";
        String appKey = "sk-ZLIjsZ2GKFpUnWNP7eB8Db92817f49CeA48574E35a5c0e3a";
        List<ChatMessage> messages = CommandClauseConvertImpl.generateChatMessageList(contents);
        ChatGPTParam data = new ChatGPTParam();
        data.setMessages(messages);
        ObjectMapper objectMapper = new ObjectMapper();
        String jsondata = objectMapper.writeValueAsString(data);
        HttpRequest req = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer " + appKey)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsondata, StandardCharsets.UTF_8))
                .build();
        HttpResponse<String> response = client.send(req,HttpResponse.BodyHandlers.ofString());
        String res = response.body().toString();
        return res;
    }
}
